package com.telit.common.aspect;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.telit.common.annotation.Log;
import com.telit.common.entity.SysOperationLog;
import com.telit.common.enums.BusinessOperatorType;
import com.telit.common.enums.BusinessStatus;
import com.telit.common.event.SysOperationLogEvent;
import com.telit.common.exception.ForestBaseException;
import com.telit.common.util.*;
import com.telit.common.util.token.User;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.HandlerMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.Map;
import java.util.Objects;


/**
 * 操作日志记录处理
 *
 * @author yuezhuang
 * @date 2022-09-19
 *         update author chencf on 2022/11/22
 */
@Slf4j
@Aspect
public class SysLogAspect {

    /**
     * 配置切入点
     */
    @Pointcut("@annotation(com.telit.common.annotation.Log)")
    public void logPointCut() {
    }

    /**
     * 处理完请求后执行
     *
     * @param joinPoint 切点
     */
    @AfterReturning(pointcut = "logPointCut()", returning = "jsonResult")
    public void doAfterReturning(JoinPoint joinPoint, Object jsonResult) {
        handleLog(joinPoint, null, jsonResult);
    }

    /**
     * 拦截异常操作
     *
     * @param joinPoint 切点
     * @param e         异常
     */
    @AfterThrowing(value = "logPointCut()", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, Exception e) {
        handleLog(joinPoint, e, null);
    }

    protected void handleLog(final JoinPoint joinPoint, final Exception e, Object jsonResult) {
        try {
            // 获得注解
            Log controllerLog = getAnnotationLog(joinPoint);
            if (controllerLog == null) {
                return;
            }

            HttpServletRequest request = Objects.requireNonNull(ServletUtils.getRequest());

            // *========数据库日志=========*//
            SysOperationLog operationLog = new SysOperationLog();
            operationLog.setStatus(BusinessStatus.SUCCESS.value());
            // 请求的地址
            operationLog.setOperIp(IpUtils.getIpAddr(request));
            // 返回参数
            operationLog.setJsonResult(JSON.toJSONString(jsonResult));
            operationLog.setOperUrl(request.getRequestURI());
            // 获取当前的用户

            User loginUser = JwtTokenUtils.getUser(request);
            if (loginUser != null) {
                operationLog.setOperName(loginUser.getRealName());
                operationLog.setDeptId(loginUser.getDeptCode());
            }
            if (e != null) {
                operationLog.setStatus(BusinessStatus.FAIL.value());
                operationLog.setErrorMsg(StringUtils.substring(e.getMessage(), 0, 2000));
            }
            // 设置方法名称
            String className = joinPoint.getTarget().getClass().getName();
            String methodName = joinPoint.getSignature().getName();
            operationLog.setMethod(className + "." + methodName + "()");
            // 设置请求方式
            operationLog.setRequestMethod(request.getMethod());
            // 操作时间
            operationLog.setOperTime(new Date());
            // 处理设置注解上的参数
            getControllerMethodDescription(joinPoint, controllerLog, operationLog);
            // 发送Spring事件保存数据库
            SpringContextHolder.publishEvent(new SysOperationLogEvent(operationLog));
        } catch (Exception exp) {
            // 记录本地异常日志
            log.error("==前置通知异常==");
            log.error("异常信息:{}", exp.getMessage());
            exp.printStackTrace();
        }
    }

    /**
     * 获取注解中对方法的描述信息 用于Controller层注解
     *
     * @param log          日志
     * @param operationLog 操作日志
     */
    public void getControllerMethodDescription(JoinPoint joinPoint, Log log, SysOperationLog operationLog) {
        // 设置action动作
        operationLog.setBusinessType(log.businessType().ordinal());
        // 设置标题
        operationLog.setService(log.service().getCode());
        // 设置操作人类别
        operationLog.setOperatorType(log.operatorType().ordinal());
        //设置业务操作类别
        operationLog.setBusinessOperatorType(log.businessOperatorType().getCode());
        //operationLog.setBusinessStatus(Integer.parseInt(String.valueOf(Integer.toString(log.businessOperatorType().getCode()).charAt(0))));

        MethodSignature method = (MethodSignature) joinPoint.getSignature();

        //获取swagger上描述信息
        String description = "";
        if (StringUtils.isBlank(log.description())) {
            // 获取swagger的描述信息
            ApiOperation apiOperation = method.getMethod().getAnnotation(ApiOperation.class);
            if (apiOperation != null && StringUtils.isNotBlank(apiOperation.value())) {
                description = apiOperation.value();
            }
        } else {
            description = log.description();
        }
        operationLog.setDescription(description);

        // 是否需要保存request，参数和值
        if (log.isSaveRequestData()) {
            // 获取参数的信息，传入到数据库中。
            setRequestValue(joinPoint, operationLog);
        }
    }

    /**
     * 获取请求的参数，放到log中
     *
     * @param operationLog 操作日志
     */
    private void setRequestValue(JoinPoint joinPoint, SysOperationLog operationLog) {
        String requestMethod = operationLog.getRequestMethod();

        String params;
        String contentType = Objects.requireNonNull(ServletUtils.getRequest()).getContentType();
        if (!StringUtils.isEmpty(contentType) && contentType.startsWith(MediaType.MULTIPART_FORM_DATA_VALUE)) {
            params = "FILE";
        } else {
            try {
                params = argsArrayToString(joinPoint.getArgs());
            } catch (IOException e) {
                throw new ForestBaseException("参数拼装失败");
            }
        }
        //火情参数中的火情状态和火情id  此可能涉及到其他处理火情，目前的做法是传userName和userCompany
        if (HttpMethod.PUT.name().equals(requestMethod) || HttpMethod.POST.name().equals(requestMethod)) {
            if (!operationLog.getOperUrl().contains("/pub")) {
                getParams(operationLog, params);
            } else {
                getPubParams(operationLog, params);
            }
            operationLog.setOperParam(StringUtils.substring(params, 0, 2000));
        } else {
            Map<?, ?> paramsMap = (Map<?, ?>) Objects.requireNonNull(ServletUtils.getRequest()).getAttribute(
                    HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
            operationLog.setOperParam(StringUtils.substring(paramsMap.toString(), 0, 1000));
            System.out.println("paramsMap = " + paramsMap);
        }
    }


    /**
     * 是否存在注解，如果存在就获取
     *
     * @param joinPoint JoinPoint
     *
     * @return Log
     */
    private Log getAnnotationLog(JoinPoint joinPoint) {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();

        if (method != null) {
            return method.getAnnotation(Log.class);
        }
        return null;
    }

    /**
     * 参数拼装
     */
    private String argsArrayToString(Object[] paramsArray) throws IOException {
        StringBuilder params = new StringBuilder();
        if (paramsArray != null && paramsArray.length > 0) {
            for (Object o : paramsArray) {
                if (!isFilterObject(o)) {
                    params.append(JSON.toJSONString(o)).append(" ");
                }
            }
        }
        return params.toString().trim();
    }


    /**
     * 判断是否需要过滤的对象。
     *
     * @param o 对象信息。
     *
     * @return 如果是需要过滤的对象，则返回true；否则返回false。
     */
    public boolean isFilterObject(final Object o) {
        return o instanceof MultipartFile || o instanceof HttpServletRequest || o instanceof HttpServletResponse;
    }


    private void getParams(SysOperationLog operationLog, String params) {
        JSONObject jsonObject = JSONObject.parseObject(params);
        Object oldStatus = jsonObject.get("oldStatus");
        Object fireId = jsonObject.get("fireId");
        Object userName = jsonObject.get("userName");
        Object userCompany = jsonObject.get("userCompany");
        Object remark = jsonObject.get("remark");
        Object businessOperatorTypeName = jsonObject.get("operatorName");
        Object operatorTime = jsonObject.get("operatorTime");
        Object eventId = jsonObject.get("eventId");
        if (Objects.nonNull(oldStatus)) {
            operationLog.setBusinessStatus(Integer.parseInt(oldStatus.toString()));
        }
        if (Objects.nonNull(fireId)) {
            operationLog.setBusinessId(fireId.toString());
        }
        if (Objects.nonNull(eventId)) {
            operationLog.setBusinessId(eventId.toString());
            operationLog.setStatus(2);
            operationLog.setBusinessStatus(2);
        }
        if (Objects.nonNull(userName)) {
            operationLog.setOperName(userName.toString());
        }
        if (Objects.nonNull(userCompany)) {
            operationLog.setDeptName(userCompany.toString());
        }
        if (Objects.nonNull(remark)) {
            operationLog.setRemark(remark.toString());
        }
        if (Objects.nonNull(businessOperatorTypeName)) {
            operationLog.setBusinessOperatorTypeName(businessOperatorTypeName.toString());
        }
        if (Objects.nonNull(operatorTime)) {
            if (operatorTime.toString().matches(DateUtils.DATE_STR_PATTERN.pattern())) {
                operationLog.setOperTime(DateUtils.parse(operatorTime.toString(), DateUtils.DATE_FORMAT));
            } else {
                operationLog.setOperTime(DateUtils.parse(operatorTime.toString(), DateUtils.yyyy_MM_dd_HH_mm_ss));
            }
        }

        if (operationLog.getBusinessOperatorType().equals(BusinessOperatorType.HQSB.getCode())
                || operationLog.getBusinessOperatorType().equals(BusinessOperatorType.HQZJ.getCode())) {
            Integer transferStatus = Integer.parseInt(jsonObject.get("transferStatus").toString());
            operationLog.setBusinessOperatorType(
                    transferStatus == 1 ? BusinessOperatorType.HQZJ.getCode() : BusinessOperatorType.HQSB.getCode());
        }
        if (operationLog.getBusinessOperatorType().equals(BusinessOperatorType.ZJQS.getCode())) {
//            Integer transferStatus = Integer.parseInt(jsonObject.get("transferStatus").toString());
//            operationLog.setBusinessOperatorType(
//                    transferStatus == 1 ? BusinessOperatorType.ZJQS.getCode() : BusinessOperatorType.SBQS.getCode());
        }
    }

    private void getPubParams(SysOperationLog operationLog, String params) {
        JSONObject jsonObject = JSONObject.parseObject(params);
        Object oldStatus = jsonObject.get("oldStatus");
        Object fireId = jsonObject.get("fireId");
        Object userName = jsonObject.get("userName");
        Object userCompany = jsonObject.get("userCompany");
        Object remark = jsonObject.get("remark");
        Object businessOperatorType = jsonObject.get("businessOperatorType");
        Object businessOperatorTypeName = jsonObject.get("operatorName");
        Object operatorTime = jsonObject.get("operatorTime");

        if (Objects.nonNull(oldStatus)) {
            operationLog.setBusinessStatus(Integer.parseInt(oldStatus.toString()));
        }
        if (Objects.nonNull(fireId)) {
            operationLog.setBusinessId(fireId.toString());
        }
        if (Objects.nonNull(userName)) {
            operationLog.setOperName(userName.toString());
        }
        if (Objects.nonNull(userCompany)) {
            operationLog.setDeptName(userCompany.toString());
        }
        if (Objects.nonNull(remark)) {
            operationLog.setRemark(remark.toString());
        }
        if (Objects.nonNull(businessOperatorType)) {
            operationLog.setBusinessOperatorType(Integer.parseInt(businessOperatorType.toString()));
        }

        if (Objects.nonNull(businessOperatorTypeName)) {
            operationLog.setBusinessOperatorTypeName(businessOperatorTypeName.toString());
        }
        if (Objects.nonNull(operatorTime)) {
            if (operatorTime.toString().matches(DateUtils.DATE_STR_PATTERN.pattern())) {
                operationLog.setOperTime(DateUtils.parse(operatorTime.toString(), DateUtils.DATE_FORMAT));
            } else {
                operationLog.setOperTime(DateUtils.parse(operatorTime.toString(), DateUtils.yyyy_MM_dd_HH_mm_ss));
            }
        }
    }

}
